<template>
  <div>
    <Modal v-model="modal" class="modal-full modal-form" :title="modalTitle" :width="modalWidth">
      <div v-if="modalShow">
        <Spin size="large" fix v-show="!modelLoad || dataLoading"></Spin>
        <Form-control
          @form-enter="formSubmit"
          v-if="modelLoad && !fetchDef"
          @validate="validateChange"
          @build="formBuild"
          :initData="defaultData"
          :module="actionModel.code+'_'+'form'"
          ref="form"
          :col="$parent.modelParam('col')||1"
          v-model="data"
          :model="formModel">
        </Form-control>
      </div>
      <div slot="footer" class="button-panel-button">
        <i-button @click="closeClick">取消</i-button>
        <ActionMirror v-if="actionModel.param && actionModel.param.inner_trigger" class="mirror-box" @triggerAction="triggerAction" :actions="innerAction"></ActionMirror>
        <Button v-if="enableStorage" @click="actionStorage" type="success" :disabled="!modelLoad || dataLoading">暂存</Button>
        <Button v-if="modelParam('path_eval')" @click="evalSubmit" type="success" :loading="evalLoading" :disabled="!modelLoad || dataLoading || !enableSubmit">{{evalName}}</Button>
        <Button v-if="actionParam.continuable && hasContinuable" @click="formSubmitContinuable" :loading="posting" :disabled="!formEnableSubmit" type="primary">保存并新增</Button>
        <Button v-if="formModel.updateAction" @click="getNewData" type="success">获取贷款最新数据</Button>
        <Button @click="formSubmit" :loading="posting" :disabled="!formEnableSubmit" type="primary">保存</Button>
      </div>
    </Modal>
    <Modal v-model="storageSaveModal" class="modal-small" title="关闭确认" :width="300">
      <div v-if="modalShow">
        <Icon type="information-circled"></Icon>
        是否保留当前的暂存数据？
      </div>
      <div slot="footer" class="button-panel-button">
        <Button @click="saveClose(false)"> 否</Button>
        <Button @click="saveClose(true)" type="success"> 是</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import Base from "../modalBase";
  import FormControl from "components/form";
  import $ from "@/common";
  import {billParser} from "@/common/parser";
  import ActionMirror from "action/actionMirror";

  const sizeWidth = {
    s: 400,
    m: 800,
    l: 900,
    max: "90%"
  };
  export default {
    extends: Base,
    props: {},
    data() {
      return {
        //使用所有者的model作为模型
        path: {
          bill_submit: "/service/{app}/bill/data/{bill_code}",
          bill_find: "/service/{app}/bill/data/{bill_code}?id={id}",
          bill_model: "/service/{app}/bill/model/{bill_code}",
          bill_def: "/service/{app}/bill/model/{bill_code}/def_value"
        },
        //扩展model加载中
        storageSaveModal: false,
        hasContinuable: false,
        modelLoad: true,
        ownerForm: true,
        modelExt: {},
        formModel: {},
        fetchDef: false,
        //默认数据
        defaultData: null,
        //首次加载状态 用于判断是否加载过model
        fristLoad: true,
        isValidate: true,
        //模型为标准的单据模板，支持默认处理
        isBillModel: true,
        //模型是否为本地文件数据，本地数据将不会通过远程链接取得默认数据
        isLocalModel: false,
        isLocalData: false,
        posting: false,
        data: {},
        tempData: {},
        dataLoading: false,
        //模型路径变化记录，用于判断是否需要重新获取数据，当模型获取路径重新生成时，该值将被赋值为true,获取model完成后将会恢复为false
        modelChange: false,
        evalLoading: false,
        hasEval: false,
        //当前表单缓存，当前只在edit中有效
        formData: {}
      }
    },
    computed: {
      formEnableSubmit() {
        if (this.enableSubmit) {
          if (this.modelParam("path_eval") && this.modelParam("eval_require")) {
            return this.hasEval;
          } else {
            return true;
          }
        } else {
          return false;
        }
      },
      evalName() {
        return this.modelParam("eval_name") || "试算";
      },
      modalWidth() {
        var size = this.$parent.modelParam("size");
        if (!size) {
          if (
            this.formModel.slaves &&
            this.formModel.slaves &&
            this.formModel.slaves.length
          ) {
            if (this.formModel.slaves && this.formModel.slaves.length > 6) {
              size = "max";
            } else {
              size = "l";
            }
          } else {
            size = "m";
          }
        }
        return sizeWidth[size];
      },
      modalTitle() {
        var name = (this.formModel && this.formModel.name) || "数据";
        return `${name}明细`;
      },
      innerAction() {
        var innerSet = new Set(this.actionModel.param.inner_trigger.split(";"));
        var data = [];
        var list = this.$parent.$parent.actionList;
        list.forEach(action => {
          if (innerSet.has(action.code)) {
            data.push(action);
          }
        });
        return data;
      },
      selectData() {
        return this.$parent.selectData;
      },
      selectValue() {
        return this.$parent.selectValue;
      },
      bill_code() {
        var bill_code = this.actionModel.bill_code || this.actionParam.bill_code;
        this.$owner = this.$owner || this.$parent.$owner;
        if (
          this.isBillModel &&
          !bill_code &&
          this.$owner &&
          this.$owner.bill_code
        ) {
          bill_code = this.$owner.bill_code;
        }
        if (bill_code) {
          return $.composeValue(bill_code, {
            ...this.actionData,
            select: this.selectData || {}
          });
        } else {
          return bill_code;
        }
      },
      //路径替换参数
      pathParam() {
        return {
          ...this.actionData,
          bill_code: this.bill_code || this.$parent.$owner.model.bill_code,
          select: this.selectData || {}
        };
      },
      modelPath() {
        let path = this.modelParam("path_model");
        if (path) {
          this.isBillModel = false;
        } else {
          this.isBillModel = true;
          path = this.path.bill_model;
        }
        return $.composePath(path, this.pathParam);
      }
    },
    watch: {
      modelPath(ov, nv) {
        if (ov !== nv) {
          this.modelChange = true;
        }
      }
    },
    created() {
      this.getFormModel();
    },
    methods: {
      getNewData() {
        $.link("/service/cs/contranct_currentInfo/sync", {
          htbh: this.defaultData.contract_code
        }).then(res => {
          for (let i in res.data) {
            this.defaultData[i] = res.data[i];
          }
          this.$refs.form.setData(this.defaultData);
        });
      },
      closeClick() {
        if (this.enableStorage && this.storageData) {
          this.storageSaveModal = true;
        } else {
          this.close();
        }
      },
      saveClose(v) {
        if (v) {
          this.storageClose();
        } else {
          this.close();
        }
        this.storageSaveModal = false;
      },
      load() {
        this.hasEval = false;
        this.isValidate = true;
      },
      updateData() {
      },
      formBuild() {
        this.$refs.form && (this.$refs.form.$parentAction = this);
      },
      getFormModel() {
        //从所有者元素处获得模型
        var modelCode = this.modelParam("model");
        if (this.ownerForm) {
          this.formModel = this.$owner.model;
          this.billCode = this.$owner.model.bill_code;
          this.isBillModel = true;
          this.isLocalModel = false;
        }
        if (
          this.modelParam("local") &&
          !this.modelParam("bill_code") &&
          !this.modelParam("path_model") &&
          !this.modelParam("path_submit")
        ) {
          this.isLocalModel = true;
        }
        if (
          this.modelParam("local") &&
          !this.modelParam("bill_code") &&
          !this.modelParam("path_model")
        ) {
          this.isLocalData = true;
        } else {
          this.isLocalData = false;
        }
        //获取表单扩展模型
        if (modelCode) {
          this.modelLoad = false;
          this.modelLoad = true;
          this.isBillModel = false;
          require(["./model/" + modelCode], data => {
            var modelExt = data.default;
            this.isLocalModel = true;
            this.formModel = modelExt.getModel(this);
          }).catch(ex => {
          });
        } else if (
          this.modelParam("bill_code") ||
          this.modelParam("path_model")
        ) {
          //通过参数指定路径查询model
          this.modelLoad = false;
          this.billCode = this.modelParam("bill_code");
          this.isLocalModel = false;
          $.link(this.modelPath + "?enable_access_token=true", this.actionData)
            .then(res => {
              //model 格式验证
              if (
                (res.data.data && (!res.data.model && !res.data.structs)) ||
                (!res.data.data && !res.data.model && !res.data.code)
              ) {
                this.$Message.error("模型格式错误");
                throw new Error("model 格式错误", res.data);
              } else {
                this.modelChange = false;
                this.isBillModel = true;
                this.tempData = res.data.data;
                this.formModel = billParser(res.data);
                //设置初始数据

                if (res.data.data) this.formModel.data = res.data.data;
                this.modelLoad = true;
              }
            })
            .catch(() => {
              //读取失败时通过modelChange设置在load步骤重新获取模型
              if (!this.modelLoad) {
                this.modelChange = true;
              }
              this.close();
            });
        } else if (this.modelParam("slave_code")) {
          //指定本地model的子表操作
          this.isLocalModel = true;
          var slaveCode = this.modelParam("slave_code");
          this.formModel.slaves.forEach(slave => {
            if (slave.code === slaveCode) {
              this.formModel = slave;
            }
          });
        }
      },
      triggerAction(action) {
        this.$owner.actionTrigger({
          code: action.code,
          row: this.actionData,
          index: this.actionDataIndex,
          data: this.actionData.id
        });
      },
      formSubmit() {
        this.$refs.form.doValidate();
        this.$nextTick(() => {
          if (!this.enableSubmit) {
            this.$Message.error("表单验证失败!");
          } else {
            this.actionSubmit();
          }
          this.isValidate = true;
        });
      },
      evalSubmit() {
        if (this.evalName !== "获取贷款最新数据") {
          this.$refs.form.doValidate();
        }
        this.$nextTick(() => {
          if (!this.enableSubmit) {
            this.$Message.error("表单验证失败!");
          } else {
            this.evalActionSubmit();
          }
          this.isValidate = true;
        });
      },
      evalActionSubmit() {
        var data = this.getPutData();
        this.evalLoading = true;
        return $.link(this.getEvalPath(), data, {
          param: this.pathParam
        })
          .then(res => {
            if (!res.data.coverForm) this.$refs.form.importData(res.data);
            for (let x in res.data) {
              this.$parent.actionData[x] = res.data[x]
            }
            this.$refs.form.updateTip();
            this.hasEval = true;
            /**
             * @Description : 2018-06-19 修改 申请减免
             * @ModifiedBy : 判断是否获取最新数据
             * @Param data : 上个表单数据
             */
            if (this.$refs.form.getTip instanceof Function) {
              let initData = this.$refs.form.getTip();
              console.log(initData);
              if (initData.parent === undefined) {
                initData = {}
              } else {
                initData.parent.dataSyncState = true
              }
            }
          })
          .finally(() => {
            this.evalLoading = false;
          });
      },
      actionSubmit() {
        return this.putData();
      },
      validateChange(v) {
        if (this.evalName === "获取贷款最新数据") {
          this.enableSubmit = true;
        } else {
          this.enableSubmit = v;
        }
      },
      getPutData() {
        var data = this.$refs.form.getData
          ? this.$refs.form.getData()
          : this.$refs.form.formData;
        if (this.$owner.model.bill_code && this.$store.state.user) {
          data.tenantry_id = this.$store.state.user.current_tenantry.id;
        }
        return data;
      },
      putData(close = true) {
        var data = this.getPutData();
        /**
         * @Description : 2018-06-19 修改 申请减免
         * @ModifiedBy : 判断是否获取最新数据 并将值提交
         * @Param data : principal_balance
         */
        if (this.$refs.form.getTip instanceof Function) {
          let initData = this.$refs.form.getTip();
          console.log(initData);
          if (initData.parent === undefined) {
            initData = {}
          } else {
            if (!initData.parent.dataSyncState) {
              initData.parent.dataSyncState = false
            }
            data.dataSyncState = initData.parent;
          }
        }
        this.enableSubmit = false;
        this.posting = true;
        return $.link(this.getSubmitPath(), data, {
          method: "put",
          param: this.pathParam
        })
          .then(res => {
            if (close !== false) {
              this.close();
            }
            this.$parent.actionSuccess();
            this.$owner.update();
          })
          .finally(() => {
            this.posting = false;
            this.enableSubmit = true;
          });
      },
      //暂存数据,需通过外部处理并在trigger阶段传入
      //TODO：通用化暂存过程，可使用action内容暂存方法，重构中需要考虑到该种情况
      actionStorage() {
        this.$owner.$emit("action_storage", {
          action: this.actionModel,
          data: {
            model: this.formModel,
            data: this.getPutData()
          }
        });
        this.storageClose();
      },
      //通过暂存恢复数据
      actionRecover() {
        this.$set(this, "formModel", this.storageData.model);
        this.$nextTick(() => {
          this.$refs.form.setData(this.storageData.data);
        });
      },
      getEvalPath() {
        var path = this.modelParam("path_eval");
        if (path) {
          path = $.composePath(path, this.pathParam);
        }
        return path;
      },
      getSubmitPath() {
        var path =
          this.modelParam("pathSubmit") || this.modelParam("path_submit");
        if (!path) {
          path = $.composePath(this.path.bill_submit, this.pathParam);
        }
        return path;
      },
      getFindPath() {
        var path = this.modelParam("pathFind") || this.modelParam("path_find");
        if (!path) {
          path = $.composePath(this.path.bill_find, {
            ...this.pathParam,
            ...this.$parent.actionData
          });
        }
        return path;
      }
    },
    components: {
      FormControl,
      ActionMirror
    }
  };
</script>

<style lang="less">
  .modal-form {
    .mirror-box {
      display: inline;
      float: none;
      margin: 0 6px;
    }
    .ivu-modal-header,
    .ivu-modal-footer {
      z-index: 9;
      position: relative;
    }
  }

  .modal-small {
    .ivu-modal-footer {
      border-top: none;
    }
    .ivu-modal-header {
      border-bottom: none;
    }
    .ivu-icon.ivu-icon-information {
      color: #168bf3;
    }
  }
</style>
